<template>
    <div class="notice-list" v-loading="loading">
        <common-list @resert="resert" ref="commonListRef">
            <template #operate="{ scope }">
                <el-button v-if="store.btns.find((item) => item.name === '修改信息')" link type="primary" size="small" @click="setHandler(scope)">修改信息</el-button>
                <div v-if="store.btns.find((item) => item.name === '修改信息')" class="line" />
                <el-button v-if="store.btns.find((item) => item.name === '修改密码')" link type="primary" size="small" @click="changePassword(scope)">修改密码</el-button>
                <div v-if="store.btns.find((item) => item.name === '修改密码')" class="line" />
                <!-- <el-button v-if="store.btns.find((item) => item.name === '重置密码')" link type="primary" size="small" @click="resetCodeClick(scope)">重置密码</el-button>
                <div v-if="store.btns.find((item) => item.name === '重置密码')" class="line" /> -->
                <el-button v-if="store.btns.find((item) => item.name === '删除')" link type="primary" size="small" @click="deletion(scope)">删除</el-button>
                <div v-if="store.btns.find((item) => item.name === '删除')" class="line" />
                <el-button v-if="store.btns.find((item) => item.name === '详情')" link type="primary" size="small" @click="personnelDetail(scope)">详情</el-button>
            </template>
            <template #state="{ scope }">
                <el-switch
                    v-model="scope.scope.row.isActive"
                    inline-prompt
                    active-text="开"
                    inactive-text="关"
                    :active-value="0"
                    :inactive-value="1"
                    :before-change="() => stateChange($event, scope.scope.row)"
                />
            </template>
            <template #btns>
                <div class="btns">
                    <el-button type="primary" @click="addHandler">新增人员</el-button>
                    <w-button v-if="store.btns.find((item) => item.name === '批量删除')" @click="allDelete">批量删除</w-button>
                </div>
            </template>
        </common-list>
        <!-- 操作(新增人员) -->
        <el-dialog v-model="added" v-if="added" title="新增人员" width="27%" :close-on-click-modal="false">
            <el-form label-width="80px" :model="addFormData" :hide-required-asterisk="true" :rules="addRules" ref="addRuleFormRef" style="max-width: 460px">
                <el-form-item label="账户名" prop="loginName">
                    <el-input v-model="addFormData.loginName" placeholder="请输入账户名" />
                </el-form-item>
                <el-form-item label="密码" prop="pwd">
                    <el-input v-model="addFormData.pwd" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item label="姓名" prop="showName">
                    <el-input v-model="addFormData.showName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                    <el-select v-model="addFormData.roleIds" placeholder="请选择角色" style="width: 100%">
                        <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" :disabled="item.isEnable == 1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="deptId">
                    <el-select v-model="addFormData.deptId" placeholder="请选择所属部门" style="width: 100%">
                        <el-option v-for="item in departmentData" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="isActive">
                    <el-select v-model="addFormData.isActive" placeholder="请选择状态" style="width: 100%">
                        <el-option :value="0" label="启用" />
                        <el-option :value="1" label="禁用" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="added = false">取消</el-button>
                    <el-button type="primary" @click="addSubmit(addRuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(修改) -->
        <el-dialog v-model="edit" v-if="edit" title="修改人员信息" width="27%" :close-on-click-modal="false">
            <el-form label-width="80px" :model="editFormData" :hide-required-asterisk="true" :rules="editRules" ref="editRuleFormRef" style="max-width: 460px">
                <el-form-item label="账户名" prop="loginName">
                    <el-input v-model="editFormData.loginName" placeholder="请输入账户名" />
                </el-form-item>
                <el-form-item label="姓名" prop="showName">
                    <el-input v-model="editFormData.showName" placeholder="请输入姓名" />
                </el-form-item>
                <el-form-item label="角色" prop="roleId">
                    <el-select v-model="editFormData.roleId" placeholder="请选择角色" style="width: 100%">
                        <el-option v-for="item in roleData" :key="item.id" :label="item.name" :value="item.id" :disabled="item.isEnable == 1" />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属部门" prop="deptId">
                    <el-select v-model="editFormData.deptId" placeholder="请选择所属部门" style="width: 100%">
                        <el-option v-for="item in departmentData" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="isActive">
                    <el-select v-model="editFormData.isActive" placeholder="请选择状态" style="width: 100%">
                        <el-option :value="0" label="启用" />
                        <el-option :value="1" label="禁用" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="edit = false">取消</el-button>
                    <el-button type="primary" @click="editSubmit(editRuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(修改密码) -->
        <el-dialog v-model="editCode" v-if="editCode" title="修改密码" width="27%" :close-on-click-modal="false">
            <el-form label-width="80px" :model="editCodeData" :rules="codeRules" ref="codeRuleFormRef" style="max-width: 460px">
                <!-- <el-form-item label="原密码" prop="historyPassword">
                    <el-input v-model="editCodeData.historyPassword" type="password" placeholder="请输入原密码" show-password />
                </el-form-item> -->
                <el-form-item label="新密码" prop="password">
                    <el-input v-model="editCodeData.password" type="password" placeholder="请输入新密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="againPassword">
                    <el-input v-model="editCodeData.againPassword" type="password" placeholder="请再次输入新密码" show-password />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editCode = false">取消</el-button>
                    <el-button type="primary" @click="editCodeSubmit(codeRuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(重置密码) -->
        <el-dialog v-model="resetCode" v-if="resetCode" title="重置密码" width="27%" :close-on-click-modal="false">
            <el-form label-width="80px" :model="resetCodeData" :rules="resetCodeRules" ref="resetcodeRuleFormRef" style="max-width: 460px">
                <el-form-item label="新密码" prop="password">
                    <el-input v-model="resetCodeData.password" type="password" placeholder="请输入新密码" show-password />
                </el-form-item>
                <el-form-item label="确认密码" prop="againPassword">
                    <el-input v-model="resetCodeData.againPassword" type="password" placeholder="请再次输入新密码" show-password />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="resetCode = false">取消</el-button>
                    <el-button type="primary" @click="resetCodeSubmit(resetcodeRuleFormRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 操作(详情) -->
        <el-dialog v-model="detail" title="人员信息" width="27%" :disabled="true" :close-on-click-modal="false">
            <el-form label-width="80px" :model="detailsFormData" style="max-width: 460px">
                <el-form-item label="账户名">
                    <el-input v-model="detailsFormData.loginName" placeholder="无" disabled />
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="detailsFormData.showName" placeholder="无" disabled />
                </el-form-item>
                <el-form-item label="角色">
                    <el-input v-model="detailsFormData.roleName" placeholder="无" disabled />
                </el-form-item>
                <el-form-item label="所属部门">
                    <el-input v-model="detailsFormData.deptName" placeholder="无" disabled />
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="detailsFormData.isActive" placeholder="无" disabled style="width: 100%">
                        <el-option :value="0" label="启用" />
                        <el-option :value="1" label="禁用" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="detail = false">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { provide, reactive, ref } from "vue";
import commonList from "@/components/commonList.vue";
import { tableConfig, formConfig, addRules, editRules } from "./config";
import { getPersonnel, getRole, addPersonnel, updatePersonnel, getSinglePersonnel, setIsEnable, deletePersonnel, setPassword, getDepartment } from "@/service/api/personnelManagement.js";
import wButton from "@/components/wButton.vue";
import { mainStore } from "@/store/main.js";

const store = mainStore();
const switchLoading = ref(false);
const commonListRef = ref(null);
const loading = ref(false);
const added = ref(false);
const edit = ref(false);
const detail = ref(false);
const editCode = ref(false);
const resetCode = ref(false);
const resetcodeRuleFormRef = ref();
const addRuleFormRef = ref();
const editRuleFormRef = ref();
const codeRuleFormRef = ref();
const departmentData = ref();
const editFormData = ref();
const detailsFormData = ref();
const addFormData = ref();
const roleData = ref();
const editCodeData = ref();
const resetCodeData = ref();
const editCodeFormData = ref({
    userId: "",
    pwd: ""
});
const stateData = reactive({
    isActive: "",
    userId: ""
});
const stateChange = async (val, row) => {
    switchLoading.value = true;
    if (row.isActive == 0) {
        stateData.isActive = 1;
    } else if (row.isActive == 1) {
        stateData.isActive = 0;
    }
    stateData.userId = row.id;
    const res = await setIsEnable(stateData);
    switchLoading.value = false;
    if (res.code === 200) {
        ElMessage.success("修改成功！");
        return true;
    } else {
        ElMessage.error(res.message);
        row.isActive = !val;
        return false;
    }
};
const formData = reactive({ deptId: "", isActive: "", loginName: "", roleId: "", showName: "" });
const codeRules = {
    historyPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请输入原密码"));
                } else {
                    return true;
                }
            },
            trigger: "blur"
        }
    ],
    password: [
        {
            validator: (rule, value, callback) => {
                const passwordReg = /^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/;
                if (!value) {
                    callback(new Error("请输入新密码"));
                }
                // else if (editCodeData.value.password === editCodeData.value.historyPassword) {
                //     callback(new Error("新密码不能与原密码相同"));
                // }
                else if (!passwordReg.test(value)) {
                    callback(new Error("新密码不低于8位且至少同时包含一位数字和大小写字母"));
                } else {
                    return true;
                }
            },
            trigger: "blur"
        }
    ],
    againPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请再次输入新密码"));
                } else if (editCodeData.value.againPassword != editCodeData.value.password) {
                    callback(new Error("新密码不一致"));
                } else {
                    return true;
                }
            },
            trigger: "blur"
        }
    ]
};
const resetCodeRules = {
    password: [
        {
            validator: (rule, value, callback) => {
                const passwordReg = /^.*(?=.{8,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).*$/;
                if (!value) {
                    callback(new Error("请输入新密码"));
                } else if (!passwordReg.test(value)) {
                    callback(new Error("新密码不低于8位且至少同时包含一位数字和大小写字母"));
                } else {
                    return true;
                }
            },
            trigger: "blur"
        }
    ],
    againPassword: [
        {
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error("请再次输入新密码"));
                } else if (resetCodeData.value.againPassword != resetCodeData.value.password) {
                    callback(new Error("新密码不一致"));
                } else {
                    return true;
                }
            },
            trigger: "blur"
        }
    ]
};
//搜索
const resert = () => {
    Object.keys(formData).forEach((key) => (formData[key] = ""));
};
GetRole();
GetDepartment();

function GetDepartment() {
    getDepartment().then((res) => {
        if (res.code === 200) {
            departmentData.value = res.data.map((item) => ({
                label: item.name,
                value: item.id
            }));
            formConfig[2].options = res.data.map((item) => ({
                label: item.name,
                value: item.id
            }));
        }
    });
}

function GetRole() {
    getRole({}).then((res) => {
        if (res.code === 200) {
            roleData.value = res.data.list;
            formConfig[1].options = res.data.list.map((item) => ({
                label: item.name,
                value: item.id
            }));
        }
    });
}
//修改
const setHandler = (scope) => {
    loading.value = true;
    GetRole();
    GetDepartment();
    getSinglePersonnel({ userId: scope.scope.row.id })
        .then((res) => {
            if (res.code === 200) {
                loading.value = false;
                editFormData.value = res.data;
                edit.value = true;
            }
        })
        .catch((err) => (loading.value = false));
};
const editSubmit = () => {
    if (!editRuleFormRef.value) return;
    editRuleFormRef.value
        .validate((valid) => {
            if (valid) {
                const loadingInstance = ElLoading.service();
                updatePersonnel(editFormData.value).then((res) => {
                    loadingInstance.close();
                    if (res.code === 200) {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.success("修改成功！");
                        edit.value = false;
                    } else {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.error(res.message);
                        edit.value = false;
                    }
                });
            }
        })
        .catch((err) => {
            loadingInstance.close();
        });
};

const resetCodeClick = (scope) => {
    resetCodeData.value = {
        id: scope.scope.row.id,
        password: "",
        againPassword: ""
    };
    resetCode.value = true;
};
const resetCodeSubmit = () => {
    if (!resetcodeRuleFormRef.value) return;
    resetcodeRuleFormRef.value
        .validate((valid) => {
            if (valid) {
                editCodeFormData.value.userId = resetCodeData.value.id;
                editCodeFormData.value.pwd = resetCodeData.value.password;
                const loadingInstance = ElLoading.service();
                setPassword(editCodeFormData.value).then((res) => {
                    loadingInstance.close();
                    if (res.code === 200) {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.success("修改成功！");
                        resetCode.value = false;
                    } else {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.error(res.message);
                        resetCode.value = false;
                    }
                });
            }
        })
        .catch((err) => {
            loadingInstance.close();
        });
};

const changePassword = (scope) => {
    editCodeData.value = {
        id: scope.scope.row.id,
        password: "",
        againPassword: ""
    };
    editCode.value = true;
};
const editCodeSubmit = () => {
    if (!codeRuleFormRef.value) return;
    codeRuleFormRef.value
        .validate((valid) => {
            if (valid) {
                editCodeFormData.value.userId = editCodeData.value.id;
                editCodeFormData.value.pwd = editCodeData.value.password;
                const loadingInstance = ElLoading.service();
                setPassword(editCodeFormData.value).then((res) => {
                    loadingInstance.close();
                    if (res.code === 200) {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.success("修改成功！");
                        editCode.value = false;
                    } else if (res.code === 101) {
                        ElMessage.error("原密码不正确！");
                    } else {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.error(res.message);
                        editCode.value = false;
                    }
                });
            }
        })
        .catch((err) => {
            loadingInstance.close();
        });
};
//新增
const addHandler = () => {
    added.value = true;
    GetDepartment();
    GetRole();
    addFormData.value = {
        loginName: "",
        pwd: "",
        showName: "",
        roleIds: "",
        deptId: "",
        isActive: ""
    };
};
const addSubmit = () => {
    if (!addRuleFormRef.value) return;
    addRuleFormRef.value
        .validate((valid) => {
            if (valid) {
                const loadingInstance = ElLoading.service();
                addPersonnel(addFormData.value).then((res) => {
                    loadingInstance.close();
                    if (res.code === 200) {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.success("新增成功！");
                        added.value = false;
                    } else {
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.error(res.message);
                        added.value = false;
                    }
                });
            }
        })
        .catch((err) => {
            loadingInstance.close();
        });
};

//详情
const personnelDetail = (scope) => {
    loading.value = true;
    GetRole();
    GetDepartment();
    getSinglePersonnel({ userId: scope.scope.row.id })
        .then((res) => {
            if (res.code === 200) {
                loading.value = false;
                detailsFormData.value = res.data;
                detail.value = true;
            }
        })
        .catch((err) => (loading.value = false));
};

//删除
const deletion = (scope) => {
    ElMessageBox.confirm("确定删除吗?", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "删除"
    })
        .then(() => {
            loading.value = true;
            deletePersonnel({ userId: scope.scope.row.id }).then((res) => {
                loading.value = false;
                if (res.code === 200) {
                    commonListRef.value.tableRef.allSelectTable = [];
                    commonListRef.value.tableRef.getTableList();
                    ElMessage.success("删除成功！");
                } else {
                    ElMessage.error(res.message);
                }
            });
        })
        .catch(() => (loading.value = false));
};

//批量删除
const allDelete = () => {
    const choose = commonListRef.value.tableRef.allSelectTable.flat().map((item) => item.id);
    if (choose.length === 0) {
        ElMessage.warning("请选择删除项！");
    } else {
        ElMessageBox.confirm("确定删除吗?", "删除", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "删除"
        })
            .then(() => {
                loading.value = true;
                deletePersonnel({ userId: choose }).then((res) => {
                    loading.value = false;
                    if (res.code === 200) {
                        commonListRef.value.tableRef.allSelectTable = [];
                        commonListRef.value.tableRef.getTableList();
                        ElMessage.success("删除成功！");
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            })
            .catch(() => (loading.value = false));
    }
};

provide("formData", formData);
provide("formConfig", formConfig);
provide("tableConfig", tableConfig);
provide("apiFn", getPersonnel);
provide("title", "人员明细");
</script>

<style lang="less" scoped>
.notice-list {
    height: 100%;
    .line {
        display: inline-block;
        margin: 0 13px;
        width: 1px;
        height: 8px;
        border: 1px solid #dcdcdc;
    }
    .btns {
        display: flex;
        .resert {
            border: 1px solid @main-color;
            color: @main-color;
        }
    }
}
</style>
<style>
.el-message-box__btns {
    justify-content: center;
}
.el-message-box__title {
    font-weight: 600;
    color: #1b3646;
}
.el-message-box__message {
    color: #1b3646;
}
.el-dialog__title {
    font-size: 16px;
    font-weight: 600;
    color: #1b3646;
}
</style>
